var app = new Vue({
  el: "#app",
  data: {
    loading: false,
    form: {
      message: "",
      name: "",
      phone: "",
    },
    validate: {
      message: {
        show: false,
        message: "请填写询价信息",
      },
      name: {
        show: false,
        message: "请填写您的姓名",
      },
      phone: {
        show: false,
        message: "请填写您的联系方式",
      },
    },
  },
  mounted() {
    const isSubmit = sessionStorage.getItem("isSubmit");
    if (!isSubmit) {
      const $name = document.getElementById("userName");
      const $phone = document.getElementById("userPhone");
      $name && (this.form.name = $name.innerText);
      $phone && (this.form.phone = $phone.innerText);
    }
  },
  methods: {
    onSubmit() {
      if (this.loading) {
        return;
      }
      if (this.onValidate()) {
        this.loading = true;
        apiSubmit(this.form)
          .then((res) => {
            this.$message({
              type: "warning",
              message: "发布成功，请耐心等待回收商报价",
            });
            sessionStorage.setItem("isSubmit", true);
            setTimeout(() => {
              this.loading = false;
              window.location.reload();
            }, 3000);
          })
          .catch((err) => {
            this.$message.error((err && err.msg) || err);
            this.loading = false;
          });
      }
    },
    onValidate(field) {
      let isValid = true;
      // 提取通用验证逻辑到一个函数
      const validateField = (value, fieldValidator) => {
        const { field, emptyMessage, pattern, patternMessage } = fieldValidator;
        if (!value) {
          this.validate[field].show = true;
          this.validate[field].message = emptyMessage;
          isValid = false;
        } else if (pattern && !pattern.test(value)) {
          this.validate[field].show = true;
          this.validate[field].message = patternMessage;
          isValid = false;
        } else {
          this.validate[field].show = false;
        }
      };

      // 定义每个字段的验证规则
      const validators = [
        {
          field: "message",
          emptyMessage: "请填写询价信息",
        },
        {
          field: "name",
          emptyMessage: "请填写您的姓名",
        },
        {
          field: "phone",
          emptyMessage: "请填写您的联系方式",
          pattern:
            /^(?:(?:\+?86)?1[3-9]\d{9})$|^(?:(?:\d{3,4}-)?\d{7,8}(?:-\d{1,6})?)$/,
          patternMessage: "请填写正确的联系方式",
        },
      ];
      // 如果指定了 field，则只验证该字段
      if (field) {
        const fieldValidator = validators.find((v) => v.field === field);
        if (fieldValidator) {
          validateField(this.form[field], fieldValidator);
          return isValid;
        }
      } else {
        validators.forEach((validator) => {
          validateField(this.form[validator.field], validator);
        });
      }

      return isValid;
    },
  },
});
